package com.itaming.lycheeframework.core.bootstrap;

import com.itaming.lycheeframework.bootstrap.EnvironmentProcessor;
import com.itaming.lycheeframework.common.constant.FrameworkConstant;
import com.itaming.lycheeframework.support.utils.StringPool;
import com.itaming.lycheeframework.support.utils.StringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.HashMap;

/**
 * Core模块环境处理器
 *
 * @author A.Ming
 */
public class LycheeCoreEnvironmentProcessor implements EnvironmentProcessor, Ordered {

    /**
     * PropertySource 名称
     */
    private static final String PROPERTY_SOURCE_NAME = "lycheeFramework";

    /**
     * 处理环境
     *
     * @param environment 环境对象
     * @param application 应用对象
     */
    @Override
    public void process(ConfigurableEnvironment environment, SpringApplication application) {
        // 创建属性映射
        HashMap<String, Object> map = new HashMap<>();
        // 框架信息
        map.put("framework.name", FrameworkConstant.FRAMEWORK_NAME);
        map.put("framework.version", FrameworkConstant.FRAMEWORK_VERSION);
        // 项目生效的环境
        map.put("framework.project.active-profile", getActiveProfile(environment));

        // 创建 PropertySource
        MapPropertySource propertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, map);

        // 添加 PropertySource
        MutablePropertySources propertySources = environment.getPropertySources();
        if (propertySources.get(PROPERTY_SOURCE_NAME) == null) {
            propertySources.addAfter("systemEnvironment", propertySource);
        } else {
            propertySources.replace(PROPERTY_SOURCE_NAME, propertySource);
        }
    }

    /**
     * 获取项目生效的环境
     *
     * @param environment 环境
     * @return 项目生效的环境
     */
    private String getActiveProfile(ConfigurableEnvironment environment) {
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles.length == 0) {
            activeProfiles = environment.getDefaultProfiles();
        }

        return StringUtil.join(StringPool.COMMA, activeProfiles);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

}
